function [xROI,yROI] = BuildROI(ODfilt,expp,handles)

yC = 1:expp.short_px_nb;   %HORIZONTAL DIMENSION OF EXPERIMENT
xC = 1:expp.long_px_nb;

autoROIok = false;

if handles.autoROI % Find ROI and extract first approx. signal from filtered image
    % Determine pre-ROI for fitting (for initial guesses)
    mx = max(max(ODfilt));
    [I,J] = find(ODfilt == mx,1);
    wndw = 50;
    if ~(I - wndw < 1 || I + wndw > max(xC) || J - wndw < 1 || J + wndw > max(yC))
        autoROIok = true;
        
        ROI(1) = I(1);
        ROI(2) = J(1);
        
        % INTEGRATED ODfilt in diff. dimens. using pre-ROI as size (for initial guesses)
        yIntFilt = sum(ODfilt(:,ROI(2)-wndw:ROI(2)+wndw),2);
        xIntFilt = sum(ODfilt(ROI(1)-wndw:ROI(1)+wndw,:),1);
        
        % Least-squares fit of INTEGRATED ODfilt (initial guesses)
        ampGuessY = max(yIntFilt) - min(yIntFilt);
        ampGuessX = max(xIntFilt) - min(xIntFilt);
        options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
        pYtmp = fminsearch(@(p)FitGauss(p,yC,yIntFilt),[ampGuessY ROI(1) 100 min(yIntFilt)],options);
        pXtmp = fminsearch(@(p)FitGauss(p,xC,xIntFilt'),[ampGuessX ROI(2) 100 min(xIntFilt)],options);
        
        % Determining autoROI based on size of ODfilt (for real fit)
        sigmas = 4;
        xWndw = round(sigmas*pXtmp(3));
        yWndw = round(sigmas*pYtmp(3));
        xROI = ROI(2)-xWndw:ROI(2)+xWndw;
        yROI = ROI(1)-yWndw:ROI(1)+yWndw;
        
        % Remove parts of the ROI if it goes outside of the photo.
        if min(xROI) < 1
            xROI = xROI(xROI > 0);
        end
        if min(yROI) < 1
            yROI = yROI(yROI > 0);
        end
        
        if max(yROI) > expp.short_px_nb
            yROI = yROI(yROI < expp.short_px_nb + 1);
        end
        if max(xROI) > expp.long_px_nb
            xROI = xROI(xROI < expp.long_px_nb + 1);
        end
    else
        warndlg('Can''t auto-choose ROI: Estimated signal close to edge of image')
        autoROIok = false;
    end
else  % Use user-input ROI parameters to get initial fitting parameters
    % User-defined ROI
    yROI = handles.ROI(3):handles.ROI(4);
    xROI = handles.ROI(1):handles.ROI(2);
end
end

